<template>
  <div>
    <div class="chart" id="onsevenchar">
      <span>图表加载中...</span>
    </div>
  </div>
</template>
  
  <script>
import { inject, onMounted, reactive, defineEmits } from "vue";
export default {
  setup() {
    let $echarts = inject("echarts");
    // 引用后台数据
    let $http = inject("axios");
    // 创建数据
    let data = reactive({});
    let xdata = reactive([]);
    let ydata = reactive([]);

    // 处理数据
    function setData() {
      xdata = data.data.chartData.chartData.data.map(v => v.title);
      ydata = data.data.chartData.chartData.data.map(v => v.num);
    }

    // 请求后台数据
    async function getState() {
      data = await $http({ url: "/one/data" });
    }

    onMounted(() => {
      // 获取元素
      let mychart = $echarts.init(document.getElementById("onsevenchar"));
      // 调用请求
      getState().then(() => {
        setData();
        // 初始化
        mychart.setOption({
          xAxis: {
            type: "category",
            data: ["2020", "2021", "2022"]
          },
          textStyle: {
            color: "#fff",
            fontSize: 20
          },
          grid: {
            left: "1%",
            right: "1%",
            bottom: "1%",
            containLabel: true
          },
          yAxis: {
            type: "value",
            min: 0,
            max: 25,
            interval: 5,
            axisLabel: {
              formatter: "{value}%"
            }
          },
          series: [
            {
              data: [22, 18, 21],
              tooltip: {
                valueFormatter: function(value) {
                  return value + " %";
                }
              },
              type: "line",
              color: "skyblue"
            }
          ]
        });
      });
    });
    return {
      // 返回数据
      getState,
      data,
      xdata,
      ydata,
      setData
    };
  }
};
</script>
  
  <style lang="scss" scoped>
.chart {
  height: 210px;
}
</style>